package com.seahorse.youliao.job;

import com.seahorse.youliao.enums.PayStatusEnum;
import com.seahorse.youliao.service.FmsPayOrderService;
import com.seahorse.youliao.service.ScheduleJobLogService;
import com.seahorse.youliao.service.entity.FmsPayOrderDTO;
import com.seahorse.youliao.service.entity.ScheduleJobLogDTO;
import com.seahorse.youliao.utils.DateUtils;
import com.seahorse.youliao.utils.SpringContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

/**
 * @ProjectName: youliao
 * @Package: com.seahorse.youliao.job
 * @ClassName: OrderOverDueJob
 * @Description: 定时任务补偿检查订单
 * @author:songqiang
 * @Date:2020-07-14 11:27
 **/
@Slf4j
@Component
public class OrderOverDueJob {


    /**
     * 定时处理订单 cron 放在数据库schedule_config配置
     * @throws SQLException
     */
    public void execute() {

        long start = System.currentTimeMillis();
        ScheduleJobLogDTO logDTO = new ScheduleJobLogDTO();
        logDTO.setStartTime(new Date());

        FmsPayOrderDTO orderDTO = new FmsPayOrderDTO();
        orderDTO.setPayStatus(PayStatusEnum.UNIFIED_ORDER.getValue());
        log.info("定时任务补偿  查询订单下单中还未支付的数据");
        FmsPayOrderService fmsPayOrderService = (FmsPayOrderService)SpringContextUtils.getBeanByClass(FmsPayOrderService.class);
        List<FmsPayOrderDTO> list = fmsPayOrderService.getList(orderDTO);
        try {
            if(!CollectionUtils.isEmpty(list)){
                for (FmsPayOrderDTO payOrderDTO : list) {

                    if(DateUtils.getDifferentNum(payOrderDTO.getCreateTime(),new Date(),1) > 30){
                        //30分钟未支付
                        //订单还未支付处理订单为过期
                        FmsPayOrderDTO dto = new FmsPayOrderDTO();
                        dto.setId(payOrderDTO.getId());
                        dto.setPayStatus(PayStatusEnum.OVER_DUE.getValue());
                        dto.setUpdateBy("自动过期");
                        dto.setUpdateTime(new Date());
                        fmsPayOrderService.update(dto);

                    }
                }
            }
        } catch (Exception e) {
            logDTO.setResult("exception");
            logDTO.setException(e.getMessage());
            log.error(e.getMessage());
        }

        long end = System.currentTimeMillis();

        logDTO.setJobName("OrderOverDueJob");
        logDTO.setStartTime(new Date());
        logDTO.setEndTime(new Date());
        logDTO.setCostSeconds((int)(start-end)/1000);
        logDTO.setResult("success");
        logDTO.setCreateBy("job");
        logDTO.setCreateTime(new Date());
        ScheduleJobLogService jobLogService = (ScheduleJobLogService)SpringContextUtils.getBeanByClass(ScheduleJobLogService.class);
        jobLogService.insert(logDTO);
    }
}
